<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\Admin\CompanyManage\StoreRegRequest;
use App\Models\Api\CompanyContact;
use App\Models\Common\CollArea;
use App\Models\Common\CollOption;
use App\Models\Company\CompanyBasic;
use App\Models\Company\CompanyDepartment;
use App\Models\Company\CompanyJob;
use App\Models\Company\CompanyUser;
use App\Models\XS\JobXS;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Style, CustomPassword;


class CompanyManageController extends CommonController{
    public function __construct(){
    }

    /**
     * 审核职位
     * @param Request $request
     * @return mixed
     */
    public function auditPost(Request $request){
        $input = $request->only('keyword', 'type');
        $type = trim($request->type);
        $keyword = trim($request->keyword);

        $company_job = DB::table('company_job as t1')
            ->join('company_basic as t2', 't1.com_id', '=', 't2.id')
            ->join('company_users as t3', 't1.uid', '=', 't3.uid')
            ->select(
                't1.id', 't1.job_title', 't1.addtime', 't1.salary_above', 't1.salary_below',
                't1.location1', 't1.location2', 't1.location3', 't1.location4', 't1.location5',
                't2.company_name', 't2.uid', 't3.viptime'
            )->where(function($query) use ($keyword){
                if(strlen($keyword) > 0){
                    $query->where('t1.job_title', 'like', '%' . $keyword . '%')
                        ->orWhere('t2.company_name', 'like', '%' . $keyword . '%');
                }
            })->where(function($query) use ($type){
                if(strlen($type) > 0){
                    $query->where('t1.job_status', $type);
                }
            })
            ->orderBy('t1.addtime', 'desc')
            ->paginate(20);

        foreach($company_job as $v){
            $location1 = ($v->location1) ? CollArea::getAreaName($v->location1) : '';
            $location2 = ($v->location2) ? CollArea::getAreaName($v->location2) : '';
            $location3 = ($v->location3) ? CollArea::getAreaName($v->location3) : '';
            $location4 = ($v->location4) ? CollArea::getAreaName($v->location4) : '';
            $location5 = ($v->location5) ? CollArea::getAreaName($v->location5) : '';
            $location = implode(',', array_unique(arrayFilter(array($location1, $location2, $location3, $location4, $location5))));
            $v->location = trim($location, ',');
            $v->salary_above = ($v->salary_above) ? CollOption::getOptionName($v->salary_above, 'expectedsalary') : '';
            $v->salary_below = ($v->salary_below) ? CollOption::getOptionName($v->salary_below, 'expectedsalary') : '';
        }
        //分页分配参数 过滤boolean假值
        $appends = arrayFilter($input);
        //工地地区
        return Style::view('admin.company_manage.audit_post', compact('company_job', 'appends', 'type'));
    }

    /**
     * 通过审核
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function postApproved(Request $request){
        $job_id = $request->input('selected_id.*');
        foreach($job_id as $k => $v){
            CompanyJob::where('id', $v)->update([
                'job_status' => 1,
                'updatetime' => date('Y-m-d H:i:s', time()),
                'xs_status' => 0
            ]);
        }

        flash('审核成功', 'success');
        return redirect()->back();
    }

    /**
     * 删除职位
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function postDel(Request $request){
        $result = CompanyJob::where('id', $request->id)->update([
            'job_status' => 4,
            'updatetime' => date('Y-m-d H:i:s', time()),
            'xs_status' => 0
        ]);
        if($result){
            return response()->json(['status' => 0, 'msg' => '职位删除成功！']);
        }else{
            return response()->json(['status' => 1, 'msg' => '职位删除失败，请稍后重试！']);
        }
    }

    /**
     * 批量删除职位
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function postBatchDel(Request $request){
        $resume_id = $request->input('selected_id.*');
        foreach($resume_id as $k => $v){
            CompanyJob::where('id', $v)->update([
                'job_status' => 4,
                'updatetime' => date('Y-m-d H:i:s', time()),
                'xs_status' => 0
            ]);
        }
        flash('批量删除职位成功！', 'success');
        return redirect()->back();
    }

    /**
     * 修改注册信息
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function comModTwo(Request $request, $id){
        $user = CompanyUser::where('uid', $id)->first(['username', 'password', 'email', 'phone', 'uid', 'regtime', 'company_name', 'contacts',
            'viptime', 'vip_resume_number', 'vip_integral', 'vip_post_number', 'resume_number', 'integral',
            'email_id', 'mobile_id', 'qqopenid', 'wechatopenid']);
        return Style::view('admin.company_manage.com_mod_two', compact('user'));
    }

    /**
     * 提交注册信息
     * @param StoreRegRequest $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function comStoreTwo(StoreRegRequest $request){
        $input = $request->only(['username', 'password', 'email', 'phone', 'uid', 'regtime', 'company_name', 'contacts',
            'viptime', 'vip_resume_number', 'vip_integral', 'vip_post_number', 'resume_number', 'integral',
            'email_id', 'mobile_id', 'qqopenid', 'wechatopenid']);
        //判断密码是否有修改
        $user = CompanyUser::where('uid', $request->uid)->first(['password']);
        if($user->password != $input['password']){
            $input['password'] = CustomPassword::make($request->input('password'));
        }
        $input['username'] = !empty(trim($request->username)) ? trim($request->username) : null;
        $input['mobile'] = !empty(trim($request->mobile)) ? trim($request->mobile) : null;
        $input['updatetime'] = date('Y-m-d,H:i:s', time());
        $input['qqopenid'] = !empty(trim($request->qqopenid)) ? trim($request->qqopenid) : null;
        $input['wechatopenid'] = !empty(trim($request->wechatopenid)) ? trim($request->wechatopenid) : null;
        $result = CompanyUser::where('uid', $request->uid)->update($input);
        if($result){
            flash('修改企业用户成功', 'success');
            return redirect('admin/audit_post');
        }else{
            return back()->with('errors', '用户信息更新失败，请稍后重试！');
        }
    }

    /**
     * 登录企业账户中心
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function companyWelcome(Request $request, $id){
        if(auth()->guard('company')->loginUsingId($id)){
            return redirect('company/welcome');
        }else{
            return redirect('admin/audit_post');
        }
    }

    /**
     * 企业用户注册信息
     * @param Request $request
     * @return mixed
     */
    public function comUserReg(Request $request){
        $input = arrayFilter($request->only('keyword', 'vip'));
        $vip = (!empty($request->vip)) ? $request->vip : '';

        $user = CompanyUser::select(['uid', 'username', 'mobile', 'company_name', 'viptime', 'regtime', 'mobile_id', 'qqopenid', 'wechatopenid', 'stop_number'])
            ->where(function($query) use ($input){
                $keyword = (!empty($input['keyword'])) ? $input['keyword'] : '';
                if(strlen($keyword) > 0){
                    $query->where('username', 'like', '%' . $keyword . '%')
                        ->orWhere('company_name', 'like', '%' . $keyword . '%')
                        ->orWhere('mobile', 'like', '%' . $keyword . '%');
                }
            })->where(function($query) use ($vip){
                //几天内
                if($vip == 'yes'){
                    $query->where('viptime', '>', date('Y-m-d H:i:s', time()));
                }else if($vip == 'no'){
                    $query->where('viptime', '<', date('Y-m-d H:i:s', time()))
                        ->orWhere('viptime', '=', null);
                }else if($vip == 'mVip'){
                    $query->where('viptime', '>', '0000-00-00 00:00:00')
                        ->where('viptime', '<', date('Y-m-d H:i:s', time()));
                }
            })
            ->orderBy('regtime', 'desc')
            ->paginate(20);
        foreach($user as $v){
            $v->regtime = substr($v->regtime, 0, 10);
            $v->viptime = substr($v->viptime, 0, 10);
        }
        return Style::view('admin.company_manage.com_user_reg', compact('user', 'input'));
    }

    /**
     * 用户注册信息修改
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function comUserMod(Request $request, $id){
        $user = CompanyUser::where('uid', $id)->first(['username', 'password', 'mobile', 'email', 'phone', 'uid', 'regtime', 'company_name', 'contacts',
            'viptime', 'vip_resume_number', 'vip_integral', 'vip_post_number', 'resume_number', 'integral',
            'email_id', 'mobile_id', 'qqopenid', 'wechatopenid', 'wechatmpopenid', 'wechatunionid', 'device_token']);
        $user->viptime = !empty($user->viptime) ? $user->viptime : '';
        return Style::view('admin.company_manage.com_user_mod', compact('user'));
    }

    /**
     * 提交注册信息
     * @param StoreRegRequest $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function comUserStore(StoreRegRequest $request){
        $input = $request->only(['username', 'password', 'email', 'mobile', 'phone', 'company_name', 'contacts',
            'viptime', 'vip_resume_number', 'vip_integral', 'vip_post_number', 'resume_number', 'integral',
            'email_id', 'mobile_id', 'qqopenid', 'wechatopenid']);
        //判断密码是否有修改
        $user = CompanyUser::where('uid', $request->uid)->first(['password']);
        if($user->password != $input['password']){
            $input['password'] = CustomPassword::make($request->input('password'));
        }
        $input['username'] = !empty(trim($request->username)) ? trim($request->username) : null;
        $input['mobile'] = !empty(trim($request->mobile)) ? trim($request->mobile) : null;
        $input['qqopenid'] = !empty(trim($request->qqopenid)) ? trim($request->qqopenid) : null;
        $input['updatetime'] = date('Y-m-d,H:i:s', time());
        $input['viptime'] = !empty($input['viptime']) ? date('Y-m-d,H:i:s', strtotime($input['viptime'])) : null;
        $input['qqopenid'] = !empty(trim($request->qqopenid)) ? trim($request->qqopenid) : null;
        $input['wechatopenid'] = !empty(trim($request->wechatopenid)) ? trim($request->wechatopenid) : null;
        $input['wechatmpopenid'] = !empty(trim($request->wechatmpopenid)) ? trim($request->wechatmpopenid) : null;
        $input['wechatunionid'] = !empty(trim($request->wechatunionid)) ? trim($request->wechatunionid) : null;
        $input['device_token'] = !empty(trim($request->device_token)) ? trim($request->device_token) : null;
        $result = CompanyUser::where('uid', $request->uid)->update($input);
        if($result){
            flash('修改企业用户成功', 'success');
            return redirect('admin/com_user_reg');
        }else{
            return back()->with('errors', '用户信息更新失败，请稍后重试！');
        }
    }

    /**
     * 用户删除
     * 删除用户在网站所有数据
     */

    public function comUserDel($uid, $com_id = null, $crm_com_id = null){
        if(empty($com_id)){
            $com_id = CompanyBasic::where('uid', $uid)->first();
            if(!empty($com_id)){
                $com_id = $com_id->id;
            }
        }
        if(empty($crm_com_id)){
            $crm_com_id = DB::table('crm_company')->where('com_uid', $uid)->first();
            if(!empty($crm_com_id)){
                $crm_com_id = $crm_com_id->id;
            }
        }
        $num = 0;
        if(!empty($crm_com_id)){
            $num += DB::table('crm_sales_task')->where('crm_company_id', $crm_com_id)->delete();
        }
        if(!empty($com_id)){
            $num += DB::table('favorites')->where('com_id', $com_id)->delete();
        }
        $arr_com_uid = ['crm_service_task', 'crm_sales_log', 'crm_service_log', 'points', 'crm_company'];
        foreach($arr_com_uid as $v){
            $num += DB::table($v)->where('com_uid', $uid)->delete();
        }
        $arr_company_uid = ['resume_send', 'interview', 'browse_company', 'browse_job', 'browse_resume', 'buy_resume', 'part_time_sign_up',
            'part_time_sign_process', 'shieldcompanies'];
        foreach($arr_company_uid as $v){
            $num += DB::table($v)->where('company_uid', $uid)->delete();
        }
        $arr_uid = ['resume_favorite', 'company_contact', 'company_certification', 'company_photo', 'my_order', 'company_password_resets',
            'company_login_record', 'company_refresh_log', 'company_visit_record', 'company_search', 'part_time_jobs', 'crm_visit_company_record',
            'company_department', 'company_contract', 'company_job', 'company_basic', 'company_users'];

        //删除迅搜中的职位
        $job_ids = DB::table('company_job')->where('uid', $uid)->pluck('id');
        if(!empty($job_ids)){
            JobXS::deleteJob($job_ids);
        }

        foreach($arr_uid as $v){
            $num += DB::table($v)->where('uid', $uid)->delete();
        }
        if($num > 0){
            return redirect('admin/com_user_del/' . $uid . '/' . $com_id . '/' . $crm_com_id);
        }else{
            return response()->json(['status' => 0, 'msg' => '用户删除成功']);
        }
    }

    /**
     * 注册基本信息
     * @param Request $request
     * @return mixed
     */
    public function comBasicReg(Request $request){
        $input = arrayFilter($request->only('keyword'));
        $companyBasic = CompanyBasic::select(['id', 'uid', 'company_name', 'mobile', 'phone', 'contacts', 'industry'])
            ->where(function($query) use ($input){
                $keyword = (!empty($input['keyword'])) ? $input['keyword'] : '';
                if(strlen($keyword) > 0){
                    $query->where('company_name', 'like', '%' . $keyword . '%');
                }
            })
            ->with(['companyUser'])
            ->orderBy('addtime', 'desc')
            ->paginate(20);

        //dd($companyBasic->toArray());
        return Style::view('admin.company_manage.com_basic_reg', compact('companyBasic', 'input'));
    }


    /**
     * 根据用户uid找出公司主页地址
     * @return mixed
     */
    public function goComAbout(Request $request){
        $companyBasic = CompanyBasic::where('uid', $request->uid)->orderBy('updatetime', 'desc')->get();
        if(count($companyBasic) == 1){
            $id = idEncryption($companyBasic[0]->id);
            return redirect('comabout_' . $id . '.html');
        }else{
            return Style::view('admin.company_manage.go_com_about', compact('companyBasic'));
        }
    }

    /**
     * 职位批量刷新列表页
     * @param Request $request
     * @return mixed
     */
    public function postAdminRefresh(Request $request){
        $input = $request->only('keyword', 'type', 'start_time', 'end_time');
        $type = trim($request->type);
        $keyword = trim($request->keyword);
        $start_time = $input['start_time'] ? $input['start_time'] : date("Y-m-d", strtotime('-3 days'));
        $end_time = $input['end_time'] ? $input['end_time'] : date('Y-m-d', time());

        $company_job = DB::table('company_job as t1')
            ->join('company_basic as t2', 't1.com_id', '=', 't2.id')
            ->join('company_users as t3', 't3.uid', '=', 't1.uid')
            ->select(
                't1.id', 't1.job_title', 't1.addtime', 't1.updatetime',
                't2.company_name', 't2.uid',
                't3.last_login_time', 't3.viptime'
            )->where('t3.viptime', '>', date("Y-m-d H:i:s", time()))
            ->where(function($query) use ($keyword){
                if(strlen($keyword) > 0){
                    $query->where('t1.job_title', 'like', '%' . $keyword . '%')
                        ->orWhere('t2.company_name', 'like', '%' . $keyword . '%');
                }
            })->where(function($query) use ($type){
                if(strlen($type) > 0){
                    $query->where('t1.job_status', $type);
                }
            })->where(function($query) use ($start_time){
                $query->where('t1.addtime', '>=', $start_time);
            })->where(function($query) use ($end_time){
                $query->where('t1.addtime', '<=', $end_time);
            })
            ->orderBy('t1.addtime', 'desc')
            ->paginate(20);

        foreach($company_job as $v){
            $v->addtime = timeTranx($v->addtime);
            $v->updatetime = timeTranx($v->updatetime);
            $v->last_login_time = timeTranx($v->last_login_time);
        }
        //分页分配参数 过滤boolean假值
        $appends = arrayFilter($input);
        //工地地区
        return Style::view('admin.company_manage.post_admin_refresh', compact('company_job', 'appends', 'type', 'start_time', 'end_time'));
    }

    /**
     * 职位刷新
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function adminPostRefresh(Request $request){
        $job_id = $request->input('selected_id.*');
        foreach($job_id as $k => $v){
            CompanyJob::where('id', $v)->update(['updatetime' => date('Y-m-d H:i:s', time()), 'xs_status' => 0]);
        }
        flash('刷新成功', 'success');
        return redirect()->back();
    }

    /**
     * 微导出
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function microJob(Request $request, $com_id){
        //公司名字
        $companyBasic = CompanyBasic::where('id',$com_id)->first();
        //获取详细地址
        $area = substr($companyBasic->region, 0, 4) . '00';
        $companyBasic->newAddress = CollArea::getAreaName($area) . CollArea::getAreaName($companyBasic->region) . $companyBasic->address;

        $company_job = DB::table('company_job as t1')
            ->join('company_basic as t2', 't1.com_id', '=', 't2.id')
            ->select(
                't1.id as job_id', 't1.job_title', 't1.recruiting_num', 't1.salary_above', 't1.salary_below', 't1.description', 't1.contact_info',
                't2.address', 't2.id as com_id', 't2.mobile', 't2.phone', 't2.region', 't2.company_name')
            ->where('t1.job_status', '=', 1)
            ->where('t2.id', '=', $com_id)
            ->orderBy('t1.updatetime', 'desc')
            ->get();
        if(count($company_job) > 0){
            foreach($company_job as $v){
                switch($v->contact_info){
                    case 1:
                        $companydepartment = CompanyDepartment::select('mobile', 'phone')->where('com_id', '=', $v->com_id)->first();
                        if(!empty($companydepartment)){
                            $v->mobile = $companydepartment->mobile;
                            $v->phone = $companydepartment->phone;;
                        }else{
                            $v->mobile = '';
                            $v->phone = '';
                        }
                        break;
                    case 2:
                        $companycontact = CompanyContact::select('mobile', 'phone')->where('job_id', '=', $v->job_id)->first();
                        if(!empty($companycontact)){
                            $v->mobile = $companycontact->mobile;
                            $v->phone = $companycontact->phone;;
                        }else{
                            $v->mobile = '';
                            $v->phone = '';
                        }
                        break;
                    case 3:
                        $v->mobile = '';
                        $v->phone = '';
                        break;
                }
                //获取详细地址
                $area = substr($v->region, 0, 4) . '00';
                $v->newAddress = CollArea::getAreaName($area) . CollArea::getAreaName($v->region) . $v->address;
                $v->salary_above = (!empty($v->salary_above)) ? CollOption::getOptionName($v->salary_above, 'expectedsalary') : '面议';
                $v->salary_below = (!empty($v->salary_below)) ? CollOption::getOptionName($v->salary_below, 'expectedsalary') : '面议';
            }
        }
        return Style::view('admin.company_manage.microJob', compact('company_job', 'companyBasic'));
    }
}

























